<template>
    <div>
        <el-card>
            <h1 slot="header">{{$t('universityManagement.exchangeUniversity')}}</h1>
            <el-row style="padding-bottom:16px">
                <el-col :span="12">
                    <KeywordInput
                        v-model="queryForm.condition.keyWord"
                        :placeholder="$t('universityManagement.searchName')"
                        @enter="queryCollegeList"
                    />
                </el-col>
                <el-col :span="12" style="text-align:right">
                    <el-dropdown
                        trigger="click"
                        size="medium"
                        @command="handleCommand"
                        style="margin-right:10px"
                    >
                        <el-button>
                            {{$t('universityManagement.lead')}}
                            <i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="DT">
                                 {{$t('universityManagement.download')}}
                            </el-dropdown-item>
                            <el-dropdown-item command="IM">
                                 {{$t('universityManagement.importData')}}
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <el-upload
                        style="display: none;"
                        ref="upload"
                        accept=".xlsx,.xls"
                        action="/api/externalexchangeservice/ug/university/import"
                        :on-success="importSuccess"
                        :on-error="importError"
                        :auto-upload="true"
                        :show-file-list="false"
                    >
                        <span slot="trigger" ref="importBtn">{{$t('universityManagement.lead')}}</span>
                    </el-upload>
                    <el-button type="danger" @click="handleClick('DEL')">{{$t('universityManagement.delete')}}</el-button>
                    <el-button type="primary" @click="handleClick('ADD')">{{$t('universityManagement.add')}}</el-button>
                </el-col>
            </el-row>
            <edu-table
                :order="false"
                :data="tableList"
                ref="collegeTable"
                style="width: 100%"
                :total="queryForm.total_"
                :pageSize="queryForm.pageSize_"
                @page-change="onCurrentPageChange"
                @selection-change="handleSelectionChange"
            >
                <el-table-column
                    :label="$t('universityManagement.schoolName')"
                    prop="universityNameZN"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('universityManagement.schoolEnName')"
                    prop="universityNameEN"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('universityManagement.regionNameZN')"
                    prop="regionNameZN"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('universityManagement.regionNameEN')"
                    prop="regionNameEN"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column :label="$t('universityManagement.operate')">
                    <template slot-scope="scope">
                        <el-button type="text" @click.stop="operate('EDIT', scope.row)">
                            {{$t('universityManagement.edit')}}
                        </el-button>
                        <el-button type="text" @click.stop="operate('VIEW', scope.row)">
                            {{$t('universityManagement.check')}}
                        </el-button>
                    </template>
                </el-table-column>
            </edu-table>
        </el-card>

        <el-dialog
            :title="dialog.mode == 'ADD' ? '新增' : dialog.mode == 'VIEW' ? '查看' : '编辑'"
            :visible.sync="dialog.visiable"
            :close-on-click-modal="false"
            @close="dialogClose"
            @open="dialogOpen"
            width="45%"
        >
            <el-form
                label-suffix="："
                label-position="right"
                :model="dialog"
                size="small"
                ref="dialog"
                label-width="160px"
                :disabled="dialog.mode == 'VIEW'"
            >
                <el-form-item
                      :label="$t('universityManagement.schoolName')"
                    prop="universityNameZN"
                    :rules="[{ required: true, message: this.$t('universityManagement.pleaseEnterschoolName') , trigger: 'blur' }]"
                >
                    <el-input
                        v-model="dialog.universityNameZN"
                        :placeholder="$t('universityManagement.pleaseEnter')"
                        style="width:80%"
                        maxlength="50"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    :label="$t('universityManagement.schoolEnName')"
                    prop="universityNameEN"
                    :rules="[{ required: true, message:this.$t('universityManagement.pleaseEnterschoolNameEn') , trigger: 'blur' }]"
                >
                    <el-input
                        v-model="dialog.universityNameEN"
                         :placeholder="$t('universityManagement.pleaseEnter')"
                        style="width:80%"
                        maxlength="50"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    :label="$t('universityManagement.regionNameZN')"
                    prop="regionCode"
                    :rules="[{ required: true, message: this.$t('universityManagement.pleaseEnterRegion'), trigger: 'change' }]"
                >
                    <el-select
                        v-model="dialog.regionCode"
                        @change="regionSelect"
                        :placeholder="$t('universityManagement.pleaseSelect')"
                        style="width:80%"
                        filterable
                    >
                        <el-option
                            v-for="item in options.regionList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                      :label="$t('universityManagement.regionNameEN')"
                    prop="regionNameEN"
                    :rules="[
                        {
                            required: true,
                            message: this.$t('universityManagement.pleaseEnterRegionEn'),
                            trigger: ['blur,change']
                        }
                    ]"
                >
                    <el-input disabled style="width:80%" v-model="dialog.regionNameEN"></el-input>
                </el-form-item>
                <el-form-item :label="$t('universityManagement.addTime')" v-if="dialog.mode == 'VIEW'">
                    <el-input  :placeholder="$t('universityManagement.pleaseEnter')" v-model="dialog.createTime"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" v-if="dialog.mode !== 'VIEW'">
                <el-button @click="dialog.visiable = false">{{$t('universityManagement.cancel')}}</el-button>
                <el-button type="primary" @click="onSubmit">{{$t('universityManagement.determine')}}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import UTILS from 'common/src/utils/utils'
import {
    getUS,
    collegeAdd,
    collegeEdit,
    getALLCollege,
    deleteCollege,
    importColleges,
    downLoadTemplate
} from 'common/src/api/internationalExchanges/exchangeCollegeManagement'
export default {
    data() {
        return {
            queryForm: {
                total_: 0,
                pageNum_: 1,
                pageSize_: 20,
                condition: {
                    keyWord: ''
                }
            },
            tableList: [],
            multipleSelection: [],
            dialog: {
                visiable: false,
                mode: '',
                universityNameZN: '',
                universityNameEN: '',
                regionCode: '',
                regionNameZN: '',
                regionNameEN: '',
                createTime: '',
                id: ''
            },
            fileList: [],
            options: {
                regionList: []
            }
        }
    },
    mounted() {
        this.queryCollegeList()
        this.getColleges()
    },
    methods: {
        async queryCollegeList() {
            let { code, data } = await getUS(this.queryForm)
            if (code !== 200) return
            this.tableList = data.list
            this.queryForm.total_ = data.total_
            this.queryForm.pageNum_ = data.pageNum_
            this.queryForm.pageSize_ = data.pageSize_
        },
        operate(mode, row) {
            this.dialog.visiable = !this.dialog.visiable
            this.dialog.mode = mode
            for (let key in this.dialog) {
                if (key !== 'visiable' && key !== 'mode') {
                    this.dialog[key] = row[key]
                }
            }
        },
        handleClick(mode) {
            switch (mode) {
                case 'ADD':
                    this.dialog.visiable = !this.dialog.visiable
                    this.dialog.mode = mode
                    break
                case 'DEL':
                    if (this.multipleSelection.length == 0) {
                        this.$message({
                            type: 'warning',
                            message: '请先选择一条记录'
                        })
                        return
                    }
                    this.$confirm('确认删除, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        deleteCollege({ ids: this.multipleSelection }).then(res => {
                            if (res.code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                })
                                this.queryCollegeList()
                            }
                        })
                    })
                    break
            }
        },
        async getColleges() {
            let { code, data } = await getALLCollege()
            if (code !== 200) return
            this.options.regionList = data.list.map(item => {
                return {
                    value: item.code,
                    label: item.nameCN,
                    labelEN: item.nameEN
                }
            })
        },
        regionSelect(val) {
            let obj = this.options.regionList.find(item => item.value == val)
            this.dialog.regionNameZN = obj.label ? obj.label : ''
            this.dialog.regionNameEN = obj.labelEN ? obj.labelEN : ''
            let fields = this.$refs['dialog'].fields
            fields.map(item => {
                if (item.prop == 'regionNameEN') {
                    item.clearValidate()
                    return false
                }
            })
        },
        onSubmit() {
            this.$refs['dialog'].validate(valid => {
                if (valid) {
                    this.dialog.visiable = !this.dialog.visiable
                    let params = _.cloneDeep(this.dialog)
                    delete params.visiable
                    delete params.mode
                    if (this.dialog.mode == 'ADD') {
                        collegeAdd(params).then(res => {
                            if (res.code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: '新增成功'
                                })
                                this.queryCollegeList()
                            }
                        })
                    } else {
                        collegeEdit(params).then(res => {
                            if (res.code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: '保存成功'
                                })
                                this.queryCollegeList()
                            }
                        })
                    }
                } else {
                    return false
                }
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val.map(item => item.id)
        },
        onCurrentPageChange(pager) {
            this.queryForm.pageSize_ = pager.pageSize
            this.queryForm.pageNum_ = pager.pageNum
            this.queryCollegeList()
        },
        dialogOpen() {
            this.$refs['dialog'] && this.$refs['dialog'].clearValidate()
        },
        dialogClose() {
            for (let key in this.dialog) {
                if (key !== 'visiable') {
                    this.dialog[key] = ''
                }
            }
        },
        //移除文件回调
        handlerRemove(file, fileList) {
            this.fileList = []
        },
        //上传文件成功回调
        handlerSuccess(response, file, fileList) {
            let responseCode = response.code
            if (responseCode === 200) {
                this.fileList.push({
                    name: file && file.name,
                    url: file.response.data[file.name] && file.response.data[file.name].objectkey
                })
                //to do 保存上传文件路径
            } else {
                this.$message({
                    message: '文件列名错误或文件为空！',
                    type: 'error'
                })
            }
        },
        //文件超出个数限制
        handleExceed() {
            this.$message({
                message: '附件只能导入一个！',
                type: 'error'
            })
        },
        //上传文件失败回调
        handlerError(rresponse, file, fileList) {
            this.$message({
                message: '上传失败！',
                type: 'error'
            })
        },
        //上传文件类型校验
        beforeUpload(file) {
            return UTILS.checkFile(
                file,
                {
                    name: '.doc,.docx,.xls,.xlsx,.jpg,.bmp,.png,.pdf',
                    size: '0.5'
                },
                this
            )
        },
        handleCommand(command) {
            switch (command) {
                case 'DT':
                    downLoadTemplate()
                    break
                case 'IM':
                    this.$refs.importBtn.click()
                    break
            }
        },
        downloadExcell(data) {
            //输出base64编码
            function base64(s) {
                return window.btoa(unescape(encodeURIComponent(s)))
            }
            //列标题
            let str =
                '<tr><td>高校名称</td><td>高校英文名称</td><td>国家地区</td><td>国家地区英文</td></tr>'
            //循环遍历，每行加入tr标签，每个单元格加td标签
            for (let i = 0; i < data.length; i++) {
                str += '<tr>'
                str += `<td>${data[i]['universityNameZN'] + '\t'}</td><td>${data[i][
                    'universityNameEN'
                ] + '\t'}</td><td>${data[i]['regionNameZN'] + '\t'}</td><td>${data[i][
                    'regionNameEN'
                ] + '\t'}</td>`
                str += '</tr>'
            }
            //Worksheet名
            let worksheet = 'Sheet1'
            let uri = 'data:application/vnd.ms-excel;base64,'

            //下载的表格模板数据
            let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40">
      <head><meta charset='UTF-8'><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${str}</table></body></html>`
            //下载模板
            window.location.href = uri + base64(template)
        },
        importSuccess(res) {
            let { code, data } = res
            if (code == 200) {
                if (data.failData && data.failData.size > 0) {
                    let exportLIst = [...data.failData.existRegion,...data.failData.existUniversity]
                    _.uniqBy(exportLIst,'universityNameZN')
                    const h = this.$createElement
                    this.$msgbox({
                        title: '提示',
                        message: h('div', null, [
                            h('span', null, ` 导入失败${data.failData.size}条！`),
                            h(
                                'button',
                                {
                                    style: 'color: rgb(40 118 194);border:none;cursor: pointer;',
                                    on: {
                                        click: () => this.downloadExcell(exportLIst)
                                    }
                                },
                                '点击下载查看详情'
                            )
                        ]),
                        confirmButtonText: '确定'
                    })
                } else {
                    this.$message({
                        type: 'success',
                        message: '导入成功！'
                    })
                }
                this.queryCollegeList()
            } else {
                this.$eduAlert(res.msg)
            }
        },
        importError() {
            this.$message({
                type: 'warning',
                message: '导入失败，请稍后再试！'
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.el-dropdown-link {
    cursor: pointer;
    color: #409eff;
}
</style>
